<?php
	/*
	 * This file updates an image for a bookmark.
	 */
	session_start();
	include 'base_config.php';	
	header($contentType_text_html);
	header($cache);
	header($pragma);
	
	if (isset($_REQUEST['sessionid'])) {
		$session_id = $_REQUEST['sessionid'];
		$session_id =  mysql_real_escape_string($session_id);
		
		if ($session_id === session_id()) {
			
			if ($_FILES['newImage']['size'] > 0) {
				$idBookmark = $_REQUEST['idBookmark'];
				$idBookmark =  mysql_real_escape_string($idBookmark);
				$oldImg = $_REQUEST['oldImgPath'];
				$oldImg = mysql_real_escape_string($oldImg);
				
				/* Add the original filename to our target path.  
				Result is "uploads/filename.extension" */
				$nomeFicheiro = pathinfo($_FILES["newImage"]["name"], PATHINFO_FILENAME);
				$ext = pathinfo($_FILES["newImage"]["name"], PATHINFO_EXTENSION);
				$novo_nome = $idBookmark . '_[' . date('Y-m-d') . ']';
				$haystack = 'abcdefghijklmnopqrstuwxyz';
				for ($i = 0; $i < 10; $i++) {
					$pos = rand(0, strlen($haystack));
					$novo_nome .=  substr($haystack, $pos, 1);
				}
				$novo_nome .= "." . $ext;
				
				$target_path = "../logos/";
				$bookmarkImagePath = "logos/" . $novo_nome;
				if(move_uploaded_file($_FILES['newImage']['tmp_name'], $target_path . $novo_nome)) {
					$success = true;
				} else {
					$success = false;
				}
				
				if ($success) {
					$sql = "UPDATE `bookmark` SET `bookmarkImagePath` = '$bookmarkImagePath' WHERE `idBookmark` = $idBookmark";					
					
					if (mysql_query($sql)) {
						$tmp = '{"Success":"true","imgPath":"' . $bookmarkImagePath . '"}';
						// Delete old file;
						unlink('../' . $oldImg);
						echo utf8_encode($tmp);
					} else {
						$tmp = '{"Success":"false","Cause":"' . mysql_error() . '"}';
						echo utf8_decode($tmp);
					}
					mysql_close($connect);
				} else {
					$tmp = '{\"Success\":\"false\",\"Cause\":\"NO_MOVE_FILE\"}';
					echo utf8_encode($tmp);
				}
			}
		} else {
			$tmp = "{\"Success\":\"false\",\"Cause\":\"NO_SESSION\"}";
			echo utf8_encode($tmp);
			session_unset();
			session_destroy();
		}
	}